package com.weijian.demo1.service;

import com.weijian.demo1.entity.Team;
import com.weijian.demo1.entity.TeamMember;
import com.weijian.demo1.entity.User;
import com.weijian.demo1.mapper.TeamMapper;
import com.weijian.demo1.mapper.TeamMemberMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TeamService {

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private TeamMemberMapper teamMemberMapper;

    @Transactional
    public Team createTeam(Team team, Long userId) {
        team.setOwnerId(userId);
        team.setCreatedAt(LocalDateTime.now());
        team.setUpdatedAt(LocalDateTime.now());
        teamMapper.insert(team);
        
        // 创建者自动成为团队成员
        TeamMember member = new TeamMember();
        member.setTeamId(team.getId());
        member.setUserId(userId);
        member.setRole("OWNER");
        member.setJoinedAt(LocalDateTime.now());
        teamMemberMapper.insert(member);
        
        return team;
    }

    public List<Team> getTeamsByUser(Long userId) {
        return teamMapper.findByUserId(userId);
    }

    public List<Team> getAllTeams() {
        return teamMapper.findAll();
    }

    public void addMember(Long teamId, Long userId) {
        // 检查用户是否已在团队中
        boolean isMember = teamMemberMapper.existsByTeamIdAndUserId(teamId, userId);
        if (!isMember) {
            TeamMember member = new TeamMember();
            member.setTeamId(teamId);
            member.setUserId(userId);
            member.setRole("MEMBER");
            member.setJoinedAt(LocalDateTime.now());
            teamMemberMapper.insert(member);
        }
    }

    public List<User> getTeamMembers(Long teamId) {
        return teamMapper.findMembersByTeamId(teamId);
    }
}